package com.yc.jpyy.company.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.utils.manydatasource.HandlerDataSource;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.base.util.PageBean;
import com.yc.jpyy.company.service.CompanyService;
import com.yc.jpyy.utils.Tools;

@Controller
@RequestMapping(value = "/company")
@Scope("prototype")
public class CompanyController extends BaseController {

	@Autowired
	private CompanyService companyService;
	private static Logger logger = LoggerFactory
			.getLogger(CompanyController.class);

	// 新增公司
	@SuppressWarnings("finally")
	@RequestMapping(value = "/companyAdd", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String companyAdd(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		String info = request.getParameter("info");
		try {
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			System.out.println(paramsMap);
			HandlerDataSource.setDataSource(dbcode);
			String id = companyService.addCompanyDao(paramsMap);
			response.setReturnMsg(1, "操作成功");
			response.setListData(id);
			return response.toJSON();

		} catch (Exception e) {
			logger.info("新增公司异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 删除公司
	@SuppressWarnings("finally")
	@RequestMapping(value = "/delCompany", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String delCompany(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));

		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			String ids = paramsMap.get("ids").toString();
			String[] idarray = ids.split(",");
			paramsMap.put("idarray", idarray);
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			int ret = companyService.delCompanyServer(paramsMap);
			if (ret == 1) {
				response.setReturnMsg(1, "删除成功");
				return response.toJSON();
			} else {
				response.setReturnMsg(0, "删除失败");
				return response.toJSON();
			}

		} catch (Exception e) {
			logger.error("删除公司异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 删除公司
	@SuppressWarnings("finally")
	@RequestMapping(value = "/delforUpdateCompany", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String delforUpdateCompany(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));

		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			String ids = paramsMap.get("ids").toString();
			String[] idarray = ids.split(",");
			paramsMap.put("idarray", idarray);
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			int ret = companyService.delforUpdateCompanyServer(paramsMap);
			if (ret > 0) {
				response.setReturnMsg(1, "删除成功");
				return response.toJSON();
			} else {
				response.setReturnMsg(0, "删除失败");
				return response.toJSON();
			}

		} catch (Exception e) {
			logger.error("删除公司异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 查询单条公司信息
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findCompanyByID", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findCompanyByID(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			Map<String, Object> val = companyService.findCompanyByID(paramsMap);
			response.setReturnMsg(1, "查询单条数据成功");
			response.setListData(val);
			return response.toJSON();

		} catch (Exception e) {
			logger.info("查询单条数据异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("查询单条数据异常");

		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 修改公司信息
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateCompany", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateCompany(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		String info = request.getParameter("info");
		try {
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			companyService.updateCompanyDao(paramsMap);
			response.setReturnCode(1);
			response.setReturnMsg(1, "操作成功");
			return response.toJSON();
		} catch (Exception e) {
			logger.info("新增公司异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			e.printStackTrace();
		}
		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 查询所有公司信息（查询条件并且分页）
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findCompany", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findCompany(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);

			if (Tools.isNotEmpty(paramsMap.get("companytype"))) {
				String companytype = paramsMap.get("companytype").toString();
				String[] companytypeArray = companytype.split(",");
				paramsMap.put("companytypeArray", companytypeArray);
			}
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			PageBean pageBean = companyService.findCompanyDao(paramsMap);
			response.setReturnMsg(1, "操作成功");
			response.setTotalCount(pageBean.getAllRow());
			response.setTotalPage(pageBean.getTotalPage());
			response.setListData(pageBean.getList());
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 查询单条公司信息
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findExistsByName", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findExistsByName(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();

			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			int val = companyService.findExistsByNameServer(paramsMap);
			Object listData = val;
			response.setReturnMsg(1, "查询数据成功");
			response.setListData(listData);
			return response.toJSON();

		} catch (Exception e) {
			logger.info("查询数据异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("查询数据异常");

		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 查询公司名称（有分页）
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findCompanyName", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findCompanyName(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			if (Tools.isNotEmpty(paramsMap.get("companytype"))) {
				String companytype = paramsMap.get("companytype").toString();
				String[] companytypeArray = companytype.split(",");
				paramsMap.put("companytypeArray", companytypeArray);
			}
			List list = companyService.findCompanyNameServer(paramsMap);
			response.setReturnMsg(1, "查询数据成功");
			response.setListData(list);
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findCompanyName" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 查询公司名称（有分页）
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findSumDriverCountAndSumCarCountByID", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findSumDriverCountAndSumCarCountByID(
			HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			List list = companyService
					.findSumDriverCountAndSumCarCountByID(paramsMap);
			response.setReturnMsg(1, "查询数据成功");
			response.setListData(list);
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findCompanyName" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	/**
	 * 档案编号生成接口
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getArchivesNo", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getArchivesNo(
			HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String dataAcquisition = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(dataAcquisition);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = companyService.getArchivesNo(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("getArchivesNo" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}
	
	
	/**
	 * 多条件分页查询接口
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findCompanySelect", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findCompanySelect(
			HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String dataAcquisition = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(dataAcquisition);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = companyService.findCompanySelect(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("findCompanySelect" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}
	
	/**
	 * 业户经营许可证日期修改接口
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateCompanyLicenseDate", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateCompanyLicenseDate(
			HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String dataAcquisition = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(dataAcquisition);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = companyService.updateCompanyLicenseDate(paramsMap);
			resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		} catch (Exception e) {
			logger.info("updateCompanyLicenseDate" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "修改失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}


}
